<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!--  卡片试图区-->
    <el-card class="box-card">
      <!--  提示区域-->
      <el-alert title="添加商品" type="info" :center="true" :closable="false" show-icon></el-alert>

      <!--      步骤条-->
      <el-steps :active="activeIndex-0" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!--  Tab 栏区域-->
      <el-form
        ref="addFormRef"
        :rules="addFormRules"
        :model="addForm"
        label-width="80px"
        label-position="top"
      >
        <el-tabs
          :tab-position="'left'"
          v-model="activeIndex"
          :before-leave="beforeleave"
          @tab-click="tabClicked"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input placeholder="请输入商品名称" v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input placeholder="请输入商品价格" type="number" v-model="addForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input placeholder="请输入商品重量" v-model="addForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input placeholder="请输入商品数量" type="number" v-model="addForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类">
              <el-cascader
                :options="CateList"
                :props="CateListprops"
                v-model="addForm.goods_cat"
                @change="handleChange"
                filterable
                placeholder="可输入关键字搜索"
                clearable
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item :label="item.attr_name" v-for="item in manyTableData" :key="item.attr_id">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox border v-for="(val,index) in item.attr_vals" :key="index" :label="val"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" v-for="item in onlyTableData" :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!-- action 图片上传的api地址 -->
            <el-upload
              :action="uploadUrl"
              :headers="uploadHeaders"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture-card"
              :limit="5"
              :on-success="onSuccess"
            >
              <el-button size="big" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addForm.goods_introduce" :options="editorOption"></quill-editor>
            <el-button type="primary" @click="add">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <el-dialog title="图片预览" :visible.sync="previewVisible" width="50%">
      <img :src="PreviewPath" alt class="PreviewImage"/>
    </el-dialog>
  </div>
</template>

<script>
  import _ from 'lodash'

  export default {
    data() {
      return {
        activeIndex: '0',
        // 商品分类列表
        CateList: [],
        CateListprops: {
          expandTrigger: 'hover',
          value: 'cat_id',
          label: 'cat_name',
          children: 'children'
        },
        // 添加商品的表单数据对象
        addForm: {
          goods_name: '',
          goods_price: 0,
          goods_weight: 0,
          goods_cat: [],
          // 上传图片的数组
          pics: [],
          // 商品的详情描述
          goods_introduce: '',
          attrs: []
        },
        addFormRules: {
          goods_name: [
            { required: true, message: '请输入商品名称', trigger: 'blur' }
          ],
          goods_price: [
            { required: true, message: '请输入商品价格', trigger: 'blur' }
          ],
          goods_weight: [
            { required: true, message: '请输入商品重量', trigger: 'blur' }
          ],
          goods_number: [
            { required: true, message: '请输入商品数量', trigger: 'blur' }
          ]
        },
        uploadUrl: 'http://192.168.3.2:8888/api/private/v1/upload',
        //  图片上传组件的headers 请求头对象
        uploadHeaders: {
          Authorization: window.sessionStorage.getItem('token')
        },
        // 动态参数列表数据
        manyTableData: [],
        // 静态参数列表数据
        onlyTableData: [],
        PreviewPath: '',
        previewVisible: false,
        // 富文本编辑器
        editorOption: {
          theme: 'snow',
          placeholder: '请输入正文'
        }
      }
    },
    created() {
      this.getCateList()
    },
    methods: {
      // 获取所有商品分类列表
      async getCateList() {
        const { data: res } = await this.$http.get('categories').catch(e => e)
        if (res.meta.status !== 200) {
          return this.$message.error('获取商品分类失败！')
        }
        this.CateList = res.data
      },
      // 级联选择器选中项发生变化 被触发
      handleChange() {
        // console.log(this.addForm.goods_cat)
        if (this.addForm.goods_cat.length !== 3) {
          this.addForm.goods_cat = null
          this.$message({
            message: '只允许选择三级菜单',
            type: 'info'
          })
        }
      },
      beforeleave(activeName, oldactiveName) {
        if (oldactiveName === '0' && this.addForm.goods_cat.length !== 3) {
          this.$message({
            message: '请先选择商品分类',
            type: 'error'
          })
          return false
        }
      },
      async tabClicked() {
        // 证明访问的是商品参数动态面板
        if (this.activeIndex === '1') {
          const { data: res } = await this.$http.get(
            `categories/${this.cateId}/attributes`,
            {
              params: { sel: 'many' }
            }
          )
          if (res.meta.status !== 200) {
            this.$message.error('获取动态参数列表失败')
          }
          this.manyTableData = res.data
          res.data.forEach(item => {
            item.attr_vals =
              item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ')
          })
          console.log(res)
        }
        // 访问静态数据请求
        else if (this.activeIndex === '2') {
          const { data: res } = await this.$http.get(
            `categories/${this.cateId}/attributes`,
            {
              params: { sel: 'only' }
            }
          )
          if (res.meta.status !== 200) {
            this.$message.error('获取静态参数列表失败')
          }
          this.onlyTableData = res.data
          console.log(this.onlyTableData)
        }
      },
      // 处理图片预览效果
      handlePreview(file) {
        this.PreviewPath = file.response.data.url
        this.previewVisible = true
      },
      handleRemove(res) {
        // 1.获取讲到删除的图片临时路径
        const filepath = res.response.data.tmp_path
        // 2.从pics数组总,找到这个图片对应的索引值
        const i = this.addForm.pics.findIndex(x => x.pic === filepath)
        // 3.调用数组的splice 方法,把图片信息对象,从pics数组总一出
        this.addForm.pics.splice(i, 1)
        console.log(this.addForm.pics)
      },
      //监听图片上传成功后的事件
      onSuccess(res) {
        // 1.拼接得到一个图片对象
        // 2.将图片信息对象push 到pics 数组总
        const picInfo = { pic: res.data.tmp_path }
        this.addForm.pics.push(picInfo)

        console.log(this.addForm.pics)
      },
      add: function() {
        this.$refs.addFormRef.validate(async valid => {
          if (valid) {
            // 执行添加的业务逻辑
            // lodash cloneDeep(obj) 拷贝包  深拷贝
            const form = _.cloneDeep(this.addForm)
            form.goods_cat = form.goods_cat.join(',')
            // 处理动态参数和处理静态属性
            this.manyTableData.forEach(item => {
              const newInfo = {
                attr_id: item.attr_id, attr_value: item.attr_vals.join(' ')
              }
              this.addForm.attrs.push(newInfo)
            })
            this.onlyTableData.forEach(item => {
              const newInfo = {
                attr_id: item.attr_id, attr_value: item.attr_vals
              }
              this.addForm.attrs.push(newInfo)
            })
            form.attrs = this.addForm.attrs

            // 发起请求添加商品
            // 商品名称，必须是唯一
            const { data: res } = await this.$http.post('goods', form)
            if (res.meta.status !== 201) {
              return this.$message.error('添加商品失败！')
            }
            this.$message.success('添加成功！')
            this.$router.push('/goods')
            // console.log(form)
          } else {
            return this.$message.error('请填写必要的表单项目!')
          }
        })
      }
    },
    computed: {
      cateId() {
        if (this.addForm.goods_cat.length === 3) {
          return this.addForm.goods_cat[2]
        }
        return null
      }
    }
  }
</script>

<style scoped>
  .el-checkbox {
    margin: 0px 5px 0 0 !important;
  }

  .PreviewImage {
    width: 100%;
  }
</style>
